'''
Created on 4 mars 2014

'''

import os
import pickle

class Stats(object):
    '''
    classdocs
    '''


    def __init__(self, base):
        '''
        Constructor
        '''
        self.file_name = 'stats'
        if os.path.exists(self.file_name):
            self.read()
        else:
            self.d = {'total':{'wrong':0,'correct':0}}

    def read(self):
        with open(self.file_name) as f:
            self.d = pickle.load(f)
#         print(self.d)

    def write(self):
        with open(self.file_name, mode='w') as f:
            pickle.dump(self.d, f)

    def correct(self, question):
        if question in self.d.keys():
            self.d[question]['correct'] += 1
        else:
            self.d[question] = {'correct':1,'wrong':0}
        self.d['total']['correct'] += 1
        self.write()


    def wrong(self, question):
        if question in self.d.keys():
            self.d[question]['wrong'] += 1
        else:
            self.d[question] = {'correct':0,'wrong':1}
        self.d['total']['wrong'] += 1
        self.write()

    def get_wrongs(self, percentile=25):
        qty = len(self.d)*(float(percentile)/100)
        rtn = []
        for k in sorted([(x, self.d[x]['wrong']) for x in self.d.keys() if x != 'total'], key=lambda y: y[1], reverse=True):
            rtn.append(k[0])
            if len(rtn) >= qty:
                return rtn

    def get_corrects(self, percentile=25):
        qty = len(self.d)*(float(percentile)/100)
        rtn = []
        for k in sorted([(x, self.d[x]['correct']) for x in self.d.keys() if x != 'total'], key=lambda y: y[1], reverse=True):
            rtn.append(k[0])
            if len(rtn) >= qty:
                return rtn

    def get_total_correct(self):
        return self.d['total']['correct']

    def get_total_wrong(self):
        return self.d['total']['wrong']

    def __str__(self):
        out = '\n'.join(['{}:{}correct: {}\t\twrong:{}'.format(x, ' '*(20-len(x)), self.d[x]['correct'], self.d[x]['wrong']) for x in self.d.keys() if x != 'total'])
        out = "{}\n\n{}".format(out,'{}:{}correct: {}\t\twrong:{}'.format('TOTAL', ' '*(20-len('TOTAL')), self.get_total_correct(), self.get_total_wrong()))
        return out
